package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDto;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    // 增加一个控制器方法，保存套餐
    // 缺少必要的POJO、DTO类
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> save(@RequestBody SetmealDto setmealDto){
        log.info("[新增套餐 dto:{}]",setmealDto);
        // 调用SetmealService完成套餐及菜品关系的保存
        // SetmealService没有保存多表的业务方法，需要我们自己扩展
        setmealService.saveWithDish(setmealDto);
        return R.success("保存成功");
    }

    @GetMapping("/page")
    public R<Page> findByPage(Integer page,Integer pageSize,String name){
        log.info("[套餐分页查询 page:{},pageSize:{},name:{}]",page,pageSize,name);
        // 分页查询，做简单版，直接调用SetmealService拿分页数据
        // 构建分页对象
        Page pageInfo = new Page(page,pageSize);
        // 添加条件
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(name!=null&&!name.equals(""),Setmeal::getName,name);
        // 分页查询
        setmealService.page(pageInfo, queryWrapper);
        // 返回
        return R.success(pageInfo);
    }

    @DeleteMapping
    // allEntries，把setmealCache这个空间下的key全部删除
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> deleteWithIds(@RequestParam List<Long> ids){
        log.info("[批量删除套餐],{}", Arrays.toString(ids.toArray()));
        // 这次批量删除是否涉及多表,肯定要删除套餐及套餐关系表
        setmealService.deleteWithIds(ids);
        return R.success("批量删除成功");
    }
    // 使用springcache完成缓存优化
    // setmealCache::套餐分类的id_1
    // Cacheable把方法的返回值存入redis
    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId+'_'+#setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal){
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId,setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus() != null,Setmeal::getStatus,setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> list = setmealService.list(queryWrapper);
        return R.success(list);
    }
}
